package com.eqdd.yiqidian.ui.discover.workcircle;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.util.LruCache;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.request.RequestOptions;
import com.coorchice.library.SuperTextView;
import com.eqdd.annotation.datasave.DealCodeClass;
import com.eqdd.yiqidian.ListItem127Custom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.WorkCircleActivityCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.base.GlideApp;
import com.eqdd.yiqidian.bean.WorkCircleBean;
import com.eqdd.yiqidian.bean.rebuild.CommentResultBean;
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows;
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration;
import com.eqdd.yiqidian.box.span.NoLineClickSpan;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.service.LocationObservable;
import com.eqdd.yiqidian.service.UserService;
import com.eqdd.yiqidian.share.JShareDialog;
import com.eqdd.yiqidian.share.LinkShareBuilder;
import com.eqdd.yiqidian.ui.InputDialogActivity;
import com.eqdd.yiqidian.ui.companyspace.ProductInfoActivity;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.ui.select.SelectRichTextActivity;
import com.eqdd.yiqidian.ui.yiqiyue.ArticleInfoActivity;
import com.eqdd.yiqidian.utils.ClickUtil;
import com.eqdd.yiqidian.utils.CopyUtil;
import com.eqdd.yiqidian.utils.DensityUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.ImageShowUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.ShareUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.InputDialogFragment;
import com.eqdd.yiqidian.widget.UniversalImageLoader;
import com.hitomi.tilibrary.style.index.NumberIndexIndicator;
import com.hitomi.tilibrary.style.progress.ProgressBarIndicator;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.jakewharton.rxbinding.view.RxView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okrx2.adapter.FlowableBody;
import com.lzy.okrx2.adapter.FlowableResponse;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.mvc.MVCSwipeRefreshHelper;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.utils.RongDateUtils;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

public class WorkCircleActivity extends BaseActivity {
    private WorkCircleActivityCustom dataBinding;
    private ArrayList<WorkCircleBean> workCircleBeen = new ArrayList<>();
    private SlimAdapterEx<WorkCircleBean> slimAdapterEx;
    private String location;
    private MVCSwipeRefreshHelper<List<WorkCircleBean>> mvcHelper;
    private ModelRx2DataSource<WorkCircleBean> dataSource;
    private InputDialogFragment inputDialogFragment;
    private int clickedPosition;
    private Transferee transferee;
    private TransferConfig config;
    private MaterialDialog dialog;
    private MaterialDialog saveDialog;
    private Disposable subscribe;


    private SlimAdapterEx<CommentResultBean> mSlimAdapterEx;
    private SimpleDateFormat sf;
    private int pageNum;
    private String talkTo;
    private SlimAdapterEx slimTalkAdapter;
    private boolean isCommentUp;
    private int dealPos;
    private boolean isMyComment;
    private int commentId;
    private String talkContent;
    private int type;
    private MaterialDialog moreDialog;
    private int id;
    private int parentId = 0;
    private String parentUserGuid;
    private int firstCommentId;


    @DealCodeClass(classes = {MsgListActivity.class})
    public void updateWorkCircle(int num) {
        if (num == 0) {
            dataBinding.btNewMsg.setVisibility(View.GONE);
        } else {
            dataBinding.btNewMsg.setVisibility(View.VISIBLE);
            dataBinding.btNewMsg.setTextColor(Color.WHITE);
            dataBinding.btNewMsg.setText(num + "条未读消息");
        }

    }

    public static Bitmap shotRecyclerView(RecyclerView view) {
        RecyclerView.Adapter adapter = view.getAdapter();
        Bitmap bigBitmap = null;
        if (adapter != null) {
            int size = adapter.getItemCount();
            int height = 0;
            Paint paint = new Paint();
            int iHeight = 0;
            final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

            // Use 1/8th of the available memory for this memory cache.
            final int cacheSize = maxMemory / 8;
            LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
            for (int i = 0; i < size; i++) {
                RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
                adapter.onBindViewHolder(holder, i);
                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                        holder.itemView.getMeasuredHeight());
                holder.itemView.setDrawingCacheEnabled(true);
                holder.itemView.buildDrawingCache();
                Bitmap drawingCache = holder.itemView.getDrawingCache();
                if (drawingCache != null) {

                    bitmaCache.put(String.valueOf(i), drawingCache);
                }
                height += holder.itemView.getMeasuredHeight();
            }

            bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
            Canvas bigCanvas = new Canvas(bigBitmap);
            Drawable lBackground = view.getBackground();
            if (lBackground instanceof ColorDrawable) {
                ColorDrawable lColorDrawable = (ColorDrawable) lBackground;
                int lColor = lColorDrawable.getColor();
                bigCanvas.drawColor(lColor);
            }

            for (int i = 0; i < size; i++) {
                Bitmap bitmap = bitmaCache.get(String.valueOf(i));
                bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);
                iHeight += bitmap.getHeight();
                bitmap.recycle();
            }
        }
        return bigBitmap;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        isRxbus = true;
        isDealCode = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_work_circle);
        initTopTitleBar(View.VISIBLE, "工作圈");
        initTopRightText("发布", v -> {
            Bundle bundle = new Bundle();
            bundle.putString(Config.TITLE, "发工作圈");
            startActivityForResult(SelectRichTextActivity.class, bundle, Config.SELECT_RICH_TEXT);
        });
        transferee = Transferee.getDefault(this);
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
        config = TransferConfig.build()
                .setMissPlaceHolder(R.mipmap.ic_launcher_logo)
                .setErrorPlaceHolder(R.mipmap.ic_launcher_logo)
                .setProgressIndicator(new ProgressBarIndicator())
                .setIndexIndicator(new NumberIndexIndicator())
                .setImageLoader(UniversalImageLoader.with(getApplicationContext()))
                .setJustLoadHitImage(true)
                .setOnLongClcikListener((imageView, i) -> {
                    ArrayList<Object> objects = new ArrayList<>();
                    objects.add("保存图片");
                    objects.add("收藏");
                    SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
                        @Override
                        public void onInject(Object data, IViewInjector injector) {

                            injector.text(R.id.tv_content, (String) data)
                                    .clicked(R.id.tv_content, v -> {
                                        saveDialog.dismiss();
                                        saveImageByUniversal(imageView);
                                    });
                        }
                    }).updateData(objects);
                    saveDialog = new MaterialDialog.Builder(this)
                            .adapter(slimAdapterEx, new LinearLayoutManager(this))
                            .build();
                    saveDialog.show();
                })
                .create();
        ImageUtil.setImage(user.getWorkImage(), dataBinding.ivHeadBg);

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.bg_work_circle)
                .error(R.drawable.bg_work_circle);

        GlideApp.with(this)
                .asBitmap()
                .load(user.getWorkImage())
                .apply(options)
                .into(dataBinding.ivHeadBg);


        dataBinding.tvSignature.setText(user.getSignature());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.SELECT_RICH_TEXT:
                    ArrayList<String> list = (ArrayList<String>) data.getSerializableExtra("list");
                    PostRequest<HttpResult> params = OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CREATE_WORK_CIRCLE)
                            .params("companyId", user.getCompanyId())
                            .params("userGuid", user.getGuid())
                            .params("message", data.getStringExtra("content"))
                            .params("name", user.getUname())
                            .params("location", TextUtils.isEmpty(location) ? "" : location);
                    for (int i = 0; i < list.size(); i++) {
                        params.params("file", new File(list.get(i)));
                    }
                    params.execute(new DialogCallBack<HttpResult>(this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                mvcHelper.refresh();
                            }
                        }
                    });
                case Config.INPUT:
                    String content = data.getStringExtra(Config.CONTENT);
                    HttpUtil.commentWorkCircle(WorkCircleActivity.this, id, parentId, content, parentUserGuid, firstCommentId, (commentBean) -> {
                        if (slimTalkAdapter == null) {
                            mSlimAdapterEx.getData().add(0, (CommentResultBean) commentBean);
                            mSlimAdapterEx.notifyItemInserted(0);
                        } else if (isCommentUp) {
                            slimTalkAdapter.getData().add(0, (CommentResultBean) commentBean);
                            slimTalkAdapter.notifyItemInserted(0);
                        } else {
                            slimTalkAdapter.getData().add((CommentResultBean) commentBean);
                            slimTalkAdapter.notifyItemInserted(slimTalkAdapter.getData().size() - 1);
                        }
                        mvcHelper.refresh();
                    });

                    break;
            }
        } else if (resultCode == Config.CHANGE) {
            WorkCircleBean bean = (WorkCircleBean) data.getSerializableExtra("bean");
            slimAdapterEx.getData().remove(requestCode);
            slimAdapterEx.getData().add(requestCode, bean);
            slimAdapterEx.notifyItemChanged(requestCode + 1);
        } else if (resultCode == Config.DELETE) {
            slimAdapterEx.getData().remove(requestCode);
            slimAdapterEx.notifyItemRemoved(requestCode + 1);
        }
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
            OkGo.<HttpResult<String>>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_UPDATE_IMG)
                    .params("userGuid", user.getGuid())
                    .params("user", user.getUname())
                    .params("file", new File(localMedia.get(0).getCompressPath()))
                    .execute(new DialogCallBack<HttpResult<String>>(WorkCircleActivity.this) {
                        @Override
                        public void onSuccess(Response<HttpResult<String>> response) {
                            HttpResult<String> httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                ImageUtil.setImage(HttpConfig.BASE_URL_NO + httpResult.getItems(), dataBinding.ivHeadBg);
                                startService(new Intent(WorkCircleActivity.this, UserService.class));
                            }
                        }
                    });
        }
    }


    @Override
    public void initData() {
        Observable<Void> observable = RxView.clicks(dataBinding.includeTitle.getRoot()).share();
        observable.buffer(observable.debounce(200, TimeUnit.MILLISECONDS))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(voids -> {
                    if (voids.size() >= 2) {
                        dataBinding.recyclerView.smoothScrollToPosition(0);
                        mvcHelper.refresh();
                    }
                }, System.out::print);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        LocationObservable.setTime(5 * 60 * 1000);
        subscribe = LocationObservable.get()
                .subscribe(aMapLocation -> {
                    if (aMapLocation.getErrorCode() == 0) {
                        location = aMapLocation.getAddress();
                    }
                });
        assert user != null;
        dataBinding.tvName.setText(user.getUsername());
        ImageUtil.setImage(user.getIphoto(), dataBinding.ivPhoto);
        dataBinding.ivPhoto.setOnClickListener(v -> {
            Intent intent = new Intent(WorkCircleActivity.this, PersonWorkCircleActivity.class);
            intent.putExtra(Config.ID, user.getGuid());
            startActivity(intent);
        });
        dataBinding.vImageWatcher.setErrorImageRes(R.mipmap.error_picture);
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.layout_work_circle, new SlimInjector<WorkCircleBean>() {
            @Override
            public void onInject(WorkCircleBean data, IViewInjector injector) {
                try {
                    injector.imageCircle(R.id.iv_head, data.getIphoto())
                            .text(R.id.tv_city, data.getLocation())
                            .visibility(R.id.tv_city, TextUtils.isEmpty(data.getLocation()) ? View.GONE : View.VISIBLE)
                            .text(R.id.tv_depart, data.getDepartName() + " " + data.getPostName())
                            .text(R.id.tv_time, RongDateUtils.getConversationFormatDate(sf.parse(data.getCreateTime()).getTime(), WorkCircleActivity.this))
                            .with(R.id.stv_name, v -> {
                                        SuperTextView superTextView = (SuperTextView) v;
                                        superTextView.setText(data.getStaffName());
                                    }
                            )
                            .text(R.id.tv_content, data.getMessage())
                            .visibility(R.id.tv_content, TextUtils.isEmpty(data.getMessage()) ? View.GONE : View.VISIBLE)
                            .with(R.id.stv_support, v -> {
                                SuperTextView superTextView = (SuperTextView) v;
                                superTextView.setText(data.getZanCount() + "");
                                superTextView.setDrawable(getResources().getDrawable(data.isIsZan() ? R.mipmap.ic_heart_red : R.mipmap.ic_heart_hint));
                            })
                            .with(R.id.stv_msg, v -> {
                                SuperTextView superTextView = (SuperTextView) v;
                                superTextView.setText(data.getCommentCount() + "");
                                superTextView.setDrawable(getResources().getDrawable(R.mipmap.ic_comment));
                            })
                            .clicked(R.id.iv_head, v -> {
                                Bundle bundle = new Bundle();
                                bundle.putString(Config.GUID, data.getCreater());
                                startActivity(UserCardActivity.class, bundle);
                            })
                            .clicked(R.id.stv_msg, v -> {
                                clickedPosition = slimAdapterEx.getData().indexOf(data);
                                // openInput(data.getStaffName(), 0 + "");
                                commentView(data.getId(), data.getStaffName());
                            })
                            .clicked(R.id.iv_option, v -> {
                                String img = null;
                                if (data.getNewImages() != null && data.getNewImages().size() > 0) {
                                    img = data.getNewImages().get(0);
                                }

                                LinkShareBuilder builder = new LinkShareBuilder(WorkCircleActivity.this);
                                builder.setTitle((data.getMessage() == null || data.getMessage() == "") ? "工作圈" : data.getMessage())
                                        .setId(data.getId() + "")
                                        .setText((data.getMessage() == null || data.getMessage() == "") ? "工作圈" : data.getMessage())
                                        .setUrl(ShareUtil.getWorkCircleUrl(data.getId() + "", ""))
                                        .setImageUrl(img)
                                        .setSource("工作圈")
                                        .setSourceOwner(data.getCreater())
                                        .build();
                                new JShareDialog(builder, WorkCircleActivity.this).show();
                            });
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (!data.isIsZan()) {
                    injector.enable(R.id.stv_support);
                    injector.clicked(R.id.stv_support, v -> {
                        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_ZAN)
                                .params("companyId", user.getCompanyId())
                                .params("userGuid", user.getGuid())
                                .params("workCircleId", data.getId())
                                .params("companyId", user.getCompanyId())
                                .execute(new JsonCallBack<HttpResult>() {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        if (httpResult.getStatus() == 200) {
                                        }
                                    }
                                });
                        SuperTextView superTextView = ((SuperTextView) v);
                        superTextView.setText((data.getZanCount() + 1) + "");
                        superTextView.setDrawable(getResources().getDrawable(R.mipmap.ic_heart_red));
                        data.setZanCount(data.getZanCount() + 1);
                        data.setIsZan(true);
                        injector.disable(R.id.stv_support);
                        data.getUserZan().add(0, new WorkCircleBean.UserZanBean(user.getGuid(), user.getIphoto()));
                        ((SlimAdapterEx) ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter()).updateData(data.getUserZan().subList(0, data.getUserZan().size() > 3 ? 3 : data.getUserZan().size()));
                    });
                } else {
                    injector.disable(R.id.stv_support);
                }
                if (((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter() == null) {
                    ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).setLayoutManager(new LinearLayoutManager(WorkCircleActivity.this, LinearLayoutManager.HORIZONTAL, false));
                    SlimAdapterEx slimAdapterExHead = SlimAdapterEx.create().register(R.layout.list_item_head_img, new SlimInjector<WorkCircleBean.UserZanBean>() {
                        @Override
                        public void onInject(WorkCircleBean.UserZanBean data, IViewInjector injector) {
                            injector.with(R.id.iv_head_img, v -> ImageUtil.setCircleImage(data.getHeadImage(), (ImageView) v));
                        }
                    }).attachTo((RecyclerView) injector.findViewById(R.id.recyclerViewHead));
                }
                ItemClickSupport.addTo((RecyclerView) injector.findViewById(R.id.recyclerViewHead))
                        .setOnItemClickListener((recyclerView, position, v) -> {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", data.getId() + "");
                            bundle.putString("idName", "workCircleId");
                            startActivity(ZanListActivity.class, bundle);
                        });
                injector.clicked(R.id.ll_head_img, v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", data.getId() + "");
                    bundle.putString("idName", "workCircleId");
                    startActivity(ZanListActivity.class, bundle);
                });
                ((SlimAdapterEx) ((RecyclerView) injector.findViewById(R.id.recyclerViewHead)).getAdapter()).updateData(data.getUserZan().subList(0, data.getUserZan().size() > 3 ? 3 : data.getUserZan().size()));
                if (data.getType() == 0) {
                    injector.gone(R.id.layout_link);
                    if (data.getNewImages() == null || data.getNewImages().size() == 0) {
                        injector.gone(R.id.recyclerView);
                    } else {
                        injector.visible(R.id.recyclerView)
                                .with(R.id.recyclerView, view -> {
                                    RecyclerView recyclerView = (RecyclerView) view;
                                    ImageShowUtil.INSTANCE.setListImgPreview(WorkCircleActivity.this, data.getNewImages(), recyclerView, 3);
                                    if (data.getNewImages().size() > 0 && data.getNewImages().size() < 4) {
                                        injector.gone(R.id.tv_img_num);
                                    } else if (data.getNewImages().size() > 3) {
                                        injector.visible(R.id.tv_img_num)
                                                .text(R.id.tv_img_num, "+" + data.getNewImages().size());
                                    }
                                });

                    }
                } else if (data.getType() == 1) {
                    injector.gone(R.id.iv_option);
                    injector.gone(R.id.rl_img);
                    if (data.getNewImages() != null && data.getNewImages().size() > 0) {
                        injector.image(R.id.iv_link_image, data.getNewImages().get(0));
                    } else {
                        injector.image(R.id.iv_link_image, R.drawable.insert_link);
                    }
                    injector.visible(R.id.layout_link)
                            .text(R.id.tv_link_text, data.getSourceTitle())
                            .clicked(R.id.layout_link, (v) -> {
                                if ("易企阅".equals(data.getSource())) {
                                    String s = data.getSourceUrl().substring(data.getSourceUrl().lastIndexOf("=") + 1, data.getSourceUrl().length());
                                    Intent intent = new Intent(WorkCircleActivity.this, ArticleInfoActivity.class);
                                    intent.putExtra("id", Integer.parseInt(s));
                                    startActivity(intent);
                                } else if ("工作圈".equals(data.getSource())) {
                                    String s = data.getSourceUrl().substring(data.getSourceUrl().indexOf("=") + 1, data.getSourceUrl().indexOf("&"));
                                    //String s = data.getSourceUrl().substring(data.getSourceUrl().lastIndexOf("=") + 1, data.getSourceUrl().length());
                                    Intent intent = new Intent(WorkCircleActivity.this, WorkCircleInfoActivity.class);
                                    intent.putExtra("id", Integer.valueOf(s));
                                    startActivity(intent);
                                } else if ("产品信息".equals(data.getSource())) {
                                    String s = data.getSourceUrl().substring(data.getSourceUrl().lastIndexOf("=") + 1, data.getSourceUrl().length());
                                    Intent intent = new Intent(WorkCircleActivity.this, ProductInfoActivity.class);
                                    intent.putExtra(Config.ID, Integer.parseInt(s));
                                    startActivity(intent);
                                }
                            });

                }

            }
        }).attachTo(dataBinding.recyclerView);
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (position == 0) {

                        if (dialog == null) {
                            dialog = getDialog();
                        }
                        dialog.show();
                    } else {
                        position--;
                        Intent intent = new Intent(WorkCircleActivity.this, WorkCircleInfoActivity.class);
                        intent.putExtra(Config.ID, slimAdapterEx.getDataItem(position).getId());
                        intent.putExtra(Config.TYPE, slimAdapterEx.getDataItem(position).getType());
                        startActivityForResult(intent, position);
                    }
                });
        slimAdapterEx.updateData(workCircleBeen);
        dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                return OkGo.<HttpResult<List<WorkCircleBean>>>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_LIST)
                        .cacheKey(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_LIST + (page == 1 ? 0 : slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 1).getId()))
                        .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                        .retryCount(1)
                        .params("companyId", user.getCompanyId())
                        .params("userGuid", user.getGuid())
                        .params("id", page == 1 ? 0 : slimAdapterEx.getDataItem(slimAdapterEx.getData().size() - 1).getId())
                        .converter(new JsonConverter<HttpResult<List<WorkCircleBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        })
                        .adapt(new FlowableResponse<>())
                        .flatMap(httpResultResponse -> Flowable.just(httpResultResponse.body().getItems() == null ? new ArrayList<WorkCircleBean>() : httpResultResponse.body().getItems()));
            }
        }, 6);
        mvcHelper = new MVCSwipeRefreshHelper<>(dataBinding.swipeRefresh);
        mvcHelper.setNeedCheckNetwork(false);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
    }

    private void enterPicPreview(WorkCircleBean data, int pos) {
        ArrayList<LocalMedia> localMedia = new ArrayList<>();
        for (int i = 0; i < data.getNewImages().size(); i++) {
            localMedia.add(PicUtil.localMedia(data.getNewImages().get(i)));
        }
        PicUtil.previewMy(WorkCircleActivity.this, pos, localMedia, "工作圈", data.getCreater());
    }

    private MaterialDialog getDialog() {
        ArrayList<Object> objects = new ArrayList<>();
        objects.add("更改封面");
        //  objects.add("截屏");
        SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
            @Override
            public void onInject(Object data, IViewInjector injector) {

                injector.text(R.id.tv_content, (String) data);
            }
        }).updateData(objects);
        MaterialDialog build = new MaterialDialog.Builder(this)
                .adapter(slimAdapterEx, new LinearLayoutManager(this))
                .build();
        ItemClickSupport.addTo(build.getRecyclerView())
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (position == 0) {
                        dialog.dismiss();
                        PicUtil.cut(WorkCircleActivity.this, 600, 300);
                    } else if (position == 1) {
                        dialog.dismiss();
                        saveImageByUniversal(shotRecyclerView(dataBinding.recyclerView));
                    }
                });

        return build;
    }

    private void newShow(int pos, WorkCircleBean data, IViewInjector injector) {
        ArrayList<ImageView> imageViews = new ArrayList<>();
        if (data.getNewImages().size() > 0) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img1));
        }
        if (data.getNewImages().size() > 1) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img2));
        }
        if (data.getNewImages().size() > 2) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img3));
        }
        config.setNowThumbnailIndex(pos);
        config.setSourceImageList(data.getNewImages());
        config.setOriginImageList(imageViews);
        transferee.apply(config).show();
    }

    private void bigImgShow(WorkCircleBean data, IViewInjector injector, ImageView v) {
        ArrayList<ImageView> imageViews = new ArrayList<>();
        if (data.getNewImages().size() > 0) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img1));
        }
        if (data.getNewImages().size() > 1) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img2));
        }
        if (data.getNewImages().size() > 2) {
            imageViews.add((ImageView) injector.findViewById(R.id.iv_img3));
        }
        dataBinding.vImageWatcher.show(v, imageViews, data.getNewImages());
    }


    private void openInput(String replyName, String replyGuid) {
        if (user.getGuid().equals(replyGuid)) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("hint", "回复" + replyName + ":");
        inputDialogFragment.setArguments(bundle);
        inputDialogFragment.show(getSupportFragmentManager(), "input");

    }

    private void commentView(int id, String creater) {
        initDialog(id, creater);
    }

    @Override
    public void setView() {
        initInputDialog();
        dataBinding.llRoot.removeViewAt(0);
        slimAdapterEx.addHeader(dataBinding.rlHeadRoot);
        ClickUtil.click(dataBinding.btNewMsg, () -> {
            dataBinding.btNewMsg.setVisibility(View.GONE);
            startActivity(MsgListActivity.class);
        });
    }

    @Override
    public void onBackPressed() {
        if (dataBinding.vImageWatcher.isShown()) {
            dataBinding.vImageWatcher.onSingleTapConfirmed();
        } else {
            super.onBackPressed();
        }
    }

    private void initInputDialog() {
        inputDialogFragment = new InputDialogFragment();
        inputDialogFragment.setOnClickListener(s -> {
                    HttpUtil.commentWorkCircle(WorkCircleActivity.this, slimAdapterEx.getDataItem(clickedPosition).getId(), 0, s, slimAdapterEx.getDataItem(clickedPosition).getCreater(), 0, object -> {
                        inputDialogFragment.dismiss();
                        WorkCircleBean dataItem = slimAdapterEx.getDataItem(clickedPosition);
                        dataItem.setCommentCount(dataItem.getCommentCount() + 1);
                        slimAdapterEx.notifyItemChanged(clickedPosition + 1);
                    });
//
                }
        );
    }

    @Override
    protected void lastRun() {
        ((WorkCircleActivity$$DealCodeInjector) register).update1();

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!subscribe.isDisposed()) {
            subscribe.dispose();
            subscribe = null;
        }

    }


    public void initDialog(int id, String creater) {
        this.id = id;
        BottomSheetDialog shareDialog = new BottomSheetDialog(this);
        ListItem127Custom inflate = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.list_item_127, null, false);
        inflate.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        inflate.recyclerView.setNestedScrollingEnabled(false);

        initRecyclerView(inflate);
        inflate.tvMsg.setOnClickListener(v -> {
            parentId = 0;
            firstCommentId = 0;
            parentUserGuid = "";
            talkTo = creater;
            slimTalkAdapter = null;
            talkTo();
        });
        shareDialog.setContentView(inflate.getRoot());
        shareDialog.setCancelable(true);
        shareDialog.show();
    }

    private void initRecyclerView(ListItem127Custom inflate) {
        RecyclerView recyclerView = inflate.recyclerView;

        sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.CHINA);

        if (mSlimAdapterEx == null) {
            setRecyclerViewMoveFast(new LinearLayoutManager(this), recyclerView);
            mSlimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_36, new SlimInjector<CommentResultBean>() {
                @Override
                public void onInject(CommentResultBean data, IViewInjector injector) {
                    try {
                        List<CommentResultBean> commentResultBeen;
                        if (data.getList() != null) {
                            commentResultBeen = data.getList();
                        } else {
                            commentResultBeen = new ArrayList<>();
                        }
                        RecyclerView recyclerView = (RecyclerView) injector.findViewById(R.id.recyclerViewCommentComment);

                        recyclerView.setLayoutManager(new LinearLayoutManager(WorkCircleActivity.this));
                        SlimAdapterEx<CommentResultBean> slimAdapterExCommentChild = SlimAdapterEx.create().register(R.layout.list_item_37, new SlimInjector<CommentResultBean>() {
                            @Override
                            public void onInject(CommentResultBean data, IViewInjector injector) {
                                injector.with(R.id.tv_comment_comment, view -> {
                                    TextView textView = (TextView) view;
                                    SpannableString spStr = new SpannableString(data.getStaffName() + ":" + " @" + data.getParentStaffName() + " " + data.getMessage());
                                    NoLineClickSpan firstSpan = new NoLineClickSpan("#3423ff", v -> {

                                        Bundle bundle = new Bundle();
                                        bundle.putString(Config.GUID, data.getCreater());
                                        startActivity(UserCardActivity.class, bundle);
                                    });
                                    NoLineClickSpan secondSpan = new NoLineClickSpan("#3423ff", v -> {
                                        Bundle bundle = new Bundle();
                                        bundle.putString(Config.GUID, data.getParentUserGuid());
                                        startActivity(UserCardActivity.class, bundle);
                                    });
                                    spStr.setSpan(firstSpan, 0, data.getStaffName().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                    spStr.setSpan(secondSpan, spStr.toString().indexOf("@"), spStr.toString().indexOf("@") + 1 + data.getParentStaffName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                    textView.setMovementMethod(LinkMovementMethod.getInstance());
                                    textView.setText(spStr);
                                });
                            }
                        }).attachTo(recyclerView).updateData(commentResultBeen);
                        ItemClickSupport.addTo(recyclerView)
                                .setOnItemClickListener((recyclerView1, position, v) -> {
                                    CommentResultBean dataItem = slimAdapterExCommentChild.getDataItem(position);
                                    isMyComment = dataItem.getCreater().equals(AppConstent.user.getGuid());
                                    commentId = dataItem.getId();
                                    parentId = dataItem.getId();
                                    parentUserGuid = dataItem.getCreater();
                                    firstCommentId = data.getId();
                                    talkTo = dataItem.getStaffName();
                                    talkContent = dataItem.getMessage();
                                    type = 2;
                                    slimTalkAdapter = slimAdapterExCommentChild;
                                    isCommentUp = false;
                                    dealPos = position;
                                    showMoreDialog();
                                });

                        injector.with(R.id.iv_comment_head, v -> ImageUtil.setCircleImage(data.getIphoto(), (ImageView) v))
                                .text(R.id.tv_comment_up_left, data.getStaffName())
                                .text(R.id.tv_comment_down_right, RongDateUtils.getConversationFormatDate(sf.parse(data.getCreateTime()).getTime(), WorkCircleActivity.this))
                                .text(R.id.tv_comment_down_left, data.getDepartName() + " " + data.getPostName())
                                .text(R.id.tv_comment, data.getMessage())
                                .visibility(R.id.tv_more_comment, data.getCommentCount() > 3 ? View.VISIBLE : View.GONE)
                                .text(R.id.tv_more_comment, String.format("展开更多%d条评论", data.getCommentCount()))
                                .clicked(R.id.tv_more_comment, v -> {

                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(Config.BEAN, data);
                                    bundle.putInt(Config.ID, id);
                                    startActivity(WorkCircleCommentActivity.class, bundle);
                                })
                                .clicked(R.id.iv_comment_comment, v -> {
                                    talkTo = data.getStaffName();
                                    parentId = data.getId();
                                    parentUserGuid = data.getCreater();
                                    firstCommentId = data.getId();
                                    slimTalkAdapter = slimAdapterExCommentChild;
                                    isCommentUp = true;
                                    dealPos = mSlimAdapterEx.getData().indexOf(data);
                                    talkTo();
                                })
                                .clicked(R.id.tv_comment, v -> {
                                    isMyComment = data.getCreater().equals(AppConstent.user.getGuid());
                                    parentId = data.getId();
                                    parentUserGuid = data.getCreater();
                                    firstCommentId = data.getId();
                                    commentId = data.getId();
                                    talkTo = data.getStaffName();
                                    talkContent = data.getMessage();
                                    type = 1;
                                    slimTalkAdapter = slimAdapterExCommentChild;
                                    isCommentUp = true;
                                    dealPos = mSlimAdapterEx.getData().indexOf(data);
                                    showMoreDialog();
                                })
                                .clicked(R.id.iv_comment_head, view -> {
                                    Bundle bundle = new Bundle();
                                    bundle.putString(Config.GUID, data.getCreater());
                                    startActivity(UserCardActivity.class, bundle);
                                });

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }).attachTo(recyclerView);
        }

        MVCCoolHelper<List<CommentResultBean>> mvcHelper = new MVCCoolHelper<>(inflate.coolRefreshView);
        ModelRx2DataSource<CommentResultBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                pageNum = page == 1 ? 0 : pageNum;

                return OkGo.<HttpResultRows<CommentResultBean>>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_COMMENT_LIST_NEW)
                        .params("workcircleId", id)
                        .params("page", pageNum)
                        .converter(new JsonConverter<HttpResultRows<CommentResultBean>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        })
                        .adapt(new FlowableBody<>())
                        .flatMap(listHttpResult -> {
                            pageNum = listHttpResult.getItems().getPage();
                            if (listHttpResult.getStatus() == 200) {
                                return Flowable.just(listHttpResult.getItems() == null ? new ArrayList<CommentResultBean>() : listHttpResult.getItems().getRows());
                            } else {
                                ToastUtil.showShort(listHttpResult.getMsg());
                                return Flowable.just(new ArrayList<>());
                            }
                        });
            }
        }, 10);
        mSlimAdapterEx.updateData(new ArrayList());
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(mSlimAdapterEx);
        mvcHelper.refresh();

    }

    private void showMoreDialog() {
        if (moreDialog == null) {
            ArrayList<Object> objects = new ArrayList<>();
            objects.add("回复");
            objects.add("复制");
            objects.add("删除");
            SlimAdapterEx slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, new SlimInjector() {
                @Override
                public void onInject(Object data, IViewInjector injector) {

                    injector.text(R.id.tv_content, (String) data);
                }
            }).updateData(objects);
            moreDialog = new MaterialDialog.Builder(this)
                    .adapter(slimAdapterEx, new LinearLayoutManager(this))
                    .build();
            moreDialog.getRecyclerView().addItemDecoration(new SectionDividerItemDecoration(this)
                    .setHeadHeight(0)
                    .setRightPadding(DensityUtil.percentW(40))
                    .setLeftPadding(DensityUtil.percentW(40))
                    .setLastBootomHeght(0));
            ItemClickSupport.addTo(moreDialog.getRecyclerView())
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        switch (position) {
                            case 0:
                                talkTo();
                                break;
                            case 1:
                                CopyUtil.copy(talkContent);
                                break;
                            case 2:
                                HttpUtil.deleteWorkCircleComment(this, commentId, id, type, () -> {
                                    if (isCommentUp) {
                                        mSlimAdapterEx.getData().remove(dealPos);
                                        mSlimAdapterEx.notifyItemRemoved(dealPos);
                                    } else {
                                        slimTalkAdapter.getData().remove(dealPos);
                                        slimTalkAdapter.notifyItemRemoved(dealPos);
                                    }
                                    mvcHelper.refresh();
                                });
                                break;
                        }
                        moreDialog.dismiss();
                    });
        }
        SlimAdapterEx slimAdapterExMore = (SlimAdapterEx) moreDialog.getRecyclerView().getAdapter();
        if (isMyComment && slimAdapterExMore.getData().size() == 2) {
            slimAdapterExMore.getData().add("删除");
            slimAdapterExMore.notifyItemInserted(2);
        } else if (!isMyComment && slimAdapterExMore.getData().size() == 3) {
            slimAdapterExMore.getData().remove(2);
            slimAdapterExMore.notifyItemRemoved(2);
        }
        moreDialog.show();

    }


    private void setRecyclerViewMoveFast(RecyclerView.LayoutManager layoutManager, RecyclerView recyclerView) {
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
    }

    private void talkTo() {
        Bundle bundle = new Bundle();
        bundle.putString(Config.TALK_TO, talkTo);
        startActivityForResult(InputDialogActivity.class, bundle, Config.INPUT);
    }

}
